package com.dwjm.shop.car;

import com.dwjm.shop.utils.ConnectionDatabaseForMySQLUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ShopCarDaoImpl implements ShopCarDao {
   private Connection connection = null;
   private PreparedStatement pstmt = null;
   private ResultSet rset = null;

   public ShopCarDaoImpl() {
      connection = ConnectionDatabaseForMySQLUseJdbc.getConnection();
   }

   @Override
   public boolean addToCart(ShopCar cartItem) {
      try {
         String sql = "INSERT INTO t_cart(gid, title, price, cid) VALUES(?,?,?,?)";
         pstmt = connection.prepareStatement(sql);
         pstmt.setLong(1, cartItem.getGid());
         pstmt.setString(2, cartItem.getTitle());
         pstmt.setDouble(3, cartItem.getPrice());
         pstmt.setLong(4, cartItem.getCid());
         return pstmt.executeUpdate() > 0;
      } catch (SQLException e) {
         e.printStackTrace();
         return false;
      } finally {
         closeResources();
      }
   }

   @Override
   public List<ShopCar> getCartList(Long cid) {
      List<ShopCar> cartList = new ArrayList<>();
      try {
         String sql = "SELECT * FROM t_cart WHERE cid = ?";
         pstmt = connection.prepareStatement(sql);
         pstmt.setLong(1, cid);
         rset = pstmt.executeQuery();

         while(rset.next()) {
            ShopCar item = new ShopCar();
            item.setId(rset.getLong("id"));
            item.setGid(rset.getLong("gid"));
            item.setTitle(rset.getString("title"));
            item.setPrice(rset.getDouble("price"));
            item.setCid(rset.getLong("cid"));
            cartList.add(item);
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
         closeResources();
      }
      return cartList;
   }

   @Override
   public boolean removeCartItem(Long id) {
      try {
         String sql = "DELETE FROM t_cart WHERE id = ?";
         pstmt = connection.prepareStatement(sql);
         pstmt.setLong(1, id);
         return pstmt.executeUpdate() > 0;
      } catch (SQLException e) {
         e.printStackTrace();
         return false;
      } finally {
         closeResources();
      }
   }

   private void closeResources() {
      try {
         if(rset != null) rset.close();
         if(pstmt != null) pstmt.close();
      } catch (SQLException e) {
         e.printStackTrace();
      }
   }
}
